package cn.maihe.elg.operation.centers.fuzhou.channel.service;

import cn.maihe.elg.operation.centers.fuzhou.auth.utils.FZApiCommonUtil;
import cn.maihe.elg.operation.centers.fuzhou.channel.FZBaseChannelService;
import cn.maihe.elg.operation.centers.fuzhou.config.FZMakeInfoConfig;
import cn.maihe.elg.operation.centers.fuzhou.dto.channel.ApplyInfoReqDTO;
import cn.maihe.elg.operation.centers.fuzhou.dto.channel.ChlBizRespData;
import cn.maihe.elg.operation.centers.fuzhou.dto.handler.*;
import cn.maihe.elg.operation.centers.fuzhou.enums.FZChannelMethod;
import cn.maihe.elg.operation.centers.fuzhou.enums.FileTypeNameEnum;
import cn.maihe.elg.operation.common.Constants;
import cn.maihe.elg.operation.config.ImageUploadConfig;
import cn.maihe.elg.operation.model.bo.AcceptOrderBO;
import cn.maihe.elg.operation.model.enums.*;
import cn.maihe.elg.operation.repository.entity.*;
import cn.maihe.elg.operation.service.business.BidCustomerService;
import cn.maihe.elg.operation.service.business.CustomerAttachmentService;
import cn.maihe.elg.operation.service.business.InstitutionService;
import cn.maihe.elg.operation.service.business.ProjectInfoService;
import cn.maihe.elg.operation.service.order.AcceptContentService;
import cn.maihe.elg.operation.service.order.AcceptOrderInfoService;
import cn.maihe.elg.operation.service.order.GuaranteeAttachmentInfoService;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import cn.maihe.elg.operation.utils.DateUtil;
import cn.maihe.elg.operation.utils.ElgLogger;
import cn.maihe.elg.operation.utils.IdGenerate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 出函机构支付确认到账后通知 电子保函至平台侧
 * @Author WJH
 * @Date 2021/04/21
 */
@Service
@Slf4j
public class FZApplyInfoService extends FZBaseChannelService<ApplyInfoReqDTO, ChlBizRespData> {

    @Resource
    private ElgResourceService elgResourceService;
    @Resource
    private AcceptOrderInfoService acceptOrderInfoService;
    @Resource
    private BidCustomerService bidCustomerService;
    @Resource
    private AcceptContentService acceptContentService;
    @Resource
    private InstitutionService institutionService;
    @Resource
    private FZMakeInfoConfig fzMakeInfoConfig;
    @Resource
    private GuaranteeAttachmentInfoService guaranteeAttachmentInfoService;
    @Resource
    private ProjectInfoService projectInfoService;
    @Resource
    private CustomerAttachmentService customerAttachmentService;
    @Resource
    private ImageUploadConfig imageUploadConfig;

    @Override
    protected FZChannelMethod methodEnum() {
        return FZChannelMethod.guaranteeApplyInfoPull;
    }


    public String requestApplyInfo(String param) {


        JSONObject jsonObject = JSONObject.parseObject(param);
        String orderNo = (String) jsonObject.get("order_no");

        Long centerId = getCurCenterId(CenterNoEnum.FUZHOU);
        Long orgId = getOrgId("DXDB");
        boolean exists = acceptOrderInfoService.existsCenterOrderId(centerId, orderNo);

        ApplyInfoReqDTO applyInfoReqDTO = new ApplyInfoReqDTO();

//      ChlBizRespData chlBizRespData = this.doRequest(CenterNoEnum.FUZHOU, applyInfoReqDTO, null);

//        String accessToke = CommonUtil.getAccessToke();

        String bhApplyInfo = FZApiCommonUtil.getBhApplyInfo(orderNo);
//        JSONObject applyObject = JSONObject.parseObject(bhApplyInfo);

        FZGuaranteeApplyInfoDTO fzGuaranteeApplyInfoDTO;
        if (bhApplyInfo != null) {
            fzGuaranteeApplyInfoDTO = JSON.parseObject(bhApplyInfo, FZGuaranteeApplyInfoDTO.class);
        } else {
            //{
            //  "status" : 1001,
            //  "msg" : "access_token非法或失效"
            //}

            log.error("获取[保函申请信息]失败，" + bhApplyInfo);
            throw new RuntimeException("\"获取[保函申请信息]失败，返回data数据为空");
        }

        String companyInfo = FZApiCommonUtil.getCompanyInfo(orderNo);
//        JSONObject companyInfoObject = JSONObject.parseObject(companyInfo);

        FZCompanyInfoDTO fzCompanyInfoDTO = null;
        if (companyInfo != null) {
            fzCompanyInfoDTO = JSON.parseObject(companyInfo, FZCompanyInfoDTO.class);
        } else {
            //{
            //  "status" : 1001,
            //  "msg" : "access_token非法或失效"
            //}

            log.error("获取[获取企业基本信息]失败，" + companyInfo);
            throw new RuntimeException("获取[获取企业基本信息]失败，返回data数据为空");
        }
//        if (exists) {
////            ProjectInfoDO projectInfoDO = projectInfoService.getBySectionCode(fzGuaranteeApplyInfoDTO.getBlockNumber(), centerId, orgId);
////            BidCustomerDO bidCustomerDO = bidCustomerService.getByCreditCode(fzCompanyInfoDTO.getPrincipal().getSocialCreditCode(), centerId, orgId, 0L);
////            AcceptOrderInfoDO acceptOrderInfoDO = acceptOrderInfoService.selectOne(AcceptOrderInfoDOCondition.builder()
////                    .andProjectIdEq(projectInfoDO.getId()).andBidCustomerIdEq(bidCustomerDO.getId()).build());
////            if (acceptOrderInfoDO != null) {
//            log.info("[受理订单已存在请勿重复申请]，orderNo：" + orderNo);
////            }
//        }
        if (!exists) {
            processService(fzGuaranteeApplyInfoDTO, fzCompanyInfoDTO, orderNo);
        }
        return fzCompanyInfoDTO.getPrincipal().getSocialCreditCode();
    }

    public void processService(FZGuaranteeApplyInfoDTO fzGuaranteeApplyInfoDTO, FZCompanyInfoDTO fzCompanyInfoDTO, String orderNo) {

        Long centerId = getCurCenterId(CenterNoEnum.FUZHOU);
        Long orgId = getOrgId("DXDB");
        AcceptOrderBO acceptOrderBO = this.parseApplyGuaranteeInfo(fzGuaranteeApplyInfoDTO, fzCompanyInfoDTO, orderNo);

        ProjectInfoDO projectInfoDO = projectInfoService.getBySectionCode(fzGuaranteeApplyInfoDTO.getBlockNumber(), null ,centerId, orgId);
        BidCustomerDO bidCustomerDO = bidCustomerService.getByCreditCode(fzCompanyInfoDTO.getPrincipal().getSocialCreditCode(), centerId, orgId, 0L);
        if (projectInfoDO != null && bidCustomerDO != null) {
//            AcceptOrderInfoDO dbOrderInfo = acceptOrderInfoService.selectOne(AcceptOrderInfoDOCondition.builder()
//                    .andProjectIdEq(projectInfoDO.getId()).andBidCustomerIdEq(bidCustomerDO.getId()).build());
            List<AcceptOrderInfoDO> dbOrderInfos = acceptOrderInfoService.selectList(AcceptOrderInfoDOCondition.builder()
                    .andProjectIdEq(projectInfoDO.getId()).andBidCustomerIdEq(bidCustomerDO.getId()).build());
            if (!dbOrderInfos.isEmpty()) {
                Optional<AcceptOrderInfoDO> filterDbOrderInfo = dbOrderInfos.stream().filter(
                        item -> !item.getStatus().equals(AcceptOrderStatus.CANCEL.getStatus())
                                && !item.getStatus().equals(AcceptOrderStatus.REVOKE_SUCCESS.getStatus())
                ).findFirst();
                if (filterDbOrderInfo.isPresent()) {
                    AcceptOrderInfoDO dbOrderInfo = filterDbOrderInfo.get();
                    ElgLogger.info(log, log -> log.info("保函申请订单已存在，请勿重复申请，受理订单号：{}，交易中心订单号：{}，新交易中心订单号：{}",
                            dbOrderInfo.getAcceptOrderNo(), dbOrderInfo.getCenterOrderId(), orderNo));
                    throw new RuntimeException("保函申请订单已存在，请勿重复申请，交易中心订单号：" + dbOrderInfo.getCenterOrderId());
                }
            }

//            if (dbOrderInfo != null && dbOrderInfo.getStatus() < AcceptOrderStatus.HAS_OUT_GUARANTEE.getStatus()) {
//                AcceptOrderInfoDO updateOrderInfo = new AcceptOrderInfoDO();
//                BeanUtil.copyProperties(dbOrderInfo, updateOrderInfo);
//                updateOrderInfo.setCenterOrderId(null);
//                final CopyOptions copyOption = CopyOptions.create(null, true);
//                BeanUtil.copyProperties(acceptOrderBO.getAcceptOrderInfo(), updateOrderInfo, copyOption);
//                updateOrderInfo.setAcceptOrderNo(dbOrderInfo.getAcceptOrderNo());
//                acceptOrderBO.setAcceptOrderInfo(updateOrderInfo);
//            }
        }

        acceptOrderBO = acceptOrderInfoService.saveAcceptOrderBO(acceptOrderBO);

        AcceptOrderInfoDO acceptOrderInfoDO = acceptOrderBO.getAcceptOrderInfo();
        acceptOrderBO.getFzFileInfos().stream().forEach(fzFileInfo -> {
            try {
                this.downloadFile(acceptOrderInfoDO, fzFileInfo);
            } catch (Exception e) {
                log.error("下载保存推送材料失败：{}", e.getMessage(), e);
                throw new RuntimeException("下载保存推送材料失败：" + e.getMessage(), e);
            }
        });

        if (acceptOrderInfoDO.getStatus() == null) {
            AcceptOrderInfoDO update = AcceptOrderInfoDO.builder().id(acceptOrderInfoDO.getId())
                    .status(AcceptOrderStatus.WAIT_FIRST_TRAIL.getStatus()).remark("投保材料下载成功，等待投标客户补全资料，签署投标申请书")
                    .build();
            acceptOrderInfoService.updateById(update);
        }

//        LstApplyRespDTO resp = buildResp(acceptOrderBO);

//        acceptContentService.saveOrUpdateAcceptContent(acceptOrderBO.getAcceptOrderInfo().getAcceptOrderNo(), context.getReq());

//        return resp;
    }

    /**
     * 解析 受理的清单信息
     */
    private AcceptOrderBO parseApplyGuaranteeInfo(FZGuaranteeApplyInfoDTO fzGuaranteeApplyInfoDTO, FZCompanyInfoDTO fzCompanyInfoDTO, String orderNo) {
//        LstApplyReqDTO req = context.getReq();
        long centerId = getCurCenterId(CenterNoEnum.FUZHOU);
        //固定得兴担保直开式
        InstitutionCode curInstitutionCode = InstitutionCode.deXing;
        long orgId = getOrgId(curInstitutionCode.getCode());
        InstitutionOrgCodeEnum institutionOrgCodeEnum = InstitutionOrgCodeEnum.resolve(curInstitutionCode.getCode());
        GuaranteeInstitutionDO institutionDO = institutionService.getInstitutionByCode(curInstitutionCode.getCode());
        String acceptOrderNo = IdGenerate.genAcceptOrderNo(CenterNoEnum.FUZHOU);
        FZMakeInfoConfig.CenterInfo centerInfo = fzMakeInfoConfig.getAuthConfig(CenterNoEnum.FUZHOU).getCenterInfo();

        ProjectInfoDO projectInfoDO = this.buildProjectInfo(fzGuaranteeApplyInfoDTO, centerId, orgId);
        BidCustomerDO bidCustomerDO = this.buildBidCustomerInfo(fzGuaranteeApplyInfoDTO, fzCompanyInfoDTO, centerId, orgId);
        UserDO userDO = this.buildUserInfo(fzGuaranteeApplyInfoDTO);
        AcceptOrderInfoDO acceptOrderInfoDO = this.buildAcceptOrderInfo(acceptOrderNo, orderNo, fzGuaranteeApplyInfoDTO, centerId, orgId, institutionDO);

        List<FilePushReqDTO.FileInfo> fileInfos = buildFileInfo(fzGuaranteeApplyInfoDTO, fzCompanyInfoDTO);

        //计算保费
//        CertifyCodeEnum certifyCode = CertifyCodeEnum.resolve(acceptOrderInfoDO.getCertifyCode());
//        if (certifyCode.equals(CertifyCodeEnum.HYMMZ)) {
//            acceptOrderInfoDO.setGuaranteeFee(getYouXiMZGuaranteeFee(projectInfoDO.getBidBond()));
//        } else {
        String feeRate = centerInfo.getFeeRate();
        acceptOrderInfoDO.setFeeRate(feeRate);
        Long minFeeYuan = centerInfo.getMinFeeYuan();
        acceptOrderInfoDO.setGuaranteeFee(yuan2fenLong(String.valueOf(minFeeYuan)));
//        acceptOrderInfoDO.setGuaranteeFee(calcGuaranteeFee(projectInfoDO.getBidBond(), feeRate, minFeeYuan));
//        }
        AcceptOrderBO orderBO = AcceptOrderBO.builder().centerId(centerId).orgId(orgId).fzFileInfos(fileInfos)
                .acceptOrderInfo(acceptOrderInfoDO).projectInfo(projectInfoDO).bidCustomer(bidCustomerDO).userDO(userDO).build();

        //默认投标保函类别;
        orderBO.setGuaranteeCategory(GuaranteeCategory.BID);
        //默认担保公司担保类型;
        orderBO.setGuaranteeType(GuaranteeType.GUARANTEE);

//        orderBO.setInstitutionCode(curInstitutionCode);
        orderBO.setInstitutionOrgCodeEnum(institutionOrgCodeEnum);
        orderBO.setIsInnerApply(false);

        //出函机构赋值
        acceptOrderInfoDO.setInstitutionId(institutionDO.getId());
        acceptOrderInfoDO.setGuaranteeType(orderBO.getGuaranteeType().getTypeStr());
        acceptOrderInfoDO.setGuaranteeCategory(orderBO.getGuaranteeCategory().getCategoryStr());


        return orderBO;
    }


    private AcceptOrderInfoDO buildAcceptOrderInfo(String acceptOrderNo, String orderNo, FZGuaranteeApplyInfoDTO fzGuaranteeApplyInfoDTO, long centerId, long orgId, GuaranteeInstitutionDO institutionDO) {
//        TbPolicyDto data = req.getTbPolicyDtoList().get(0);
//        TbInsuranceSchema insuranceSchema = data.getTbInsuranceSchema();
//        TbMainLiab mainLiab = data.getTbMainLiab();
//        TbProvinceSupply provinceSupply = data.getTbProvinceSupply();
//        String projectCode = mainLiab.getInsureArea();
//        String projectName = mainLiab.getBusinessDetail();

        return AcceptOrderInfoDO.builder()
                .centerId(centerId).orgId(orgId)
                .guaranteeNo(IdGenerate.genGuaranteeNo())
                .centerOrderId(orderNo)
                .centerOrderTime(DateUtil.getDatetime())
                .acceptOrderNo(acceptOrderNo)
                .projectName(fzGuaranteeApplyInfoDTO.getProjectName())
                .sectionName(fzGuaranteeApplyInfoDTO.getBlockName())
                .bidCustomerName(fzGuaranteeApplyInfoDTO.getPrincipal())
                //当前投标期限保证金截止时间
                .bidIndate(DateUtil.parseDate(fzGuaranteeApplyInfoDTO.getBidDeadline(), "yyyy-MM-dd HH:mm"))
//                .guaranteeType(null)//'保函类型'
//                .guaranteeCategory(null) //'保函品种'
//                .templateId(null)//'报价模板主键id'
//                .feeRate(null)
//                .guaranteeFee(null)//'保费金额分'
                .status(AcceptOrderStatus.WAIT_FIRST_TRAIL.getStatus())
//                .guaranteeTime(null)
//                .projectId(null)//  '投保项目主键id' 关联保存时统一设置
//                .bidCustomerId(null)// '投保客户主键id'
//                .institutionId(null) //'开函机构主键'
//                .attachmentId(null)//
//                .applyOrderNo(null)
//                .invoiceFlag(null)
//                .invoiceId(null)
                .warnFlag(0)
//                .warnContent(null)
                .gmtCreate(Date.from(Instant.now()))
                .certifyCode(fzGuaranteeApplyInfoDTO.getProjectCityCode())
                .build();
    }

    private BidCustomerDO buildBidCustomerInfo(FZGuaranteeApplyInfoDTO fzGuaranteeApplyInfoDTO, FZCompanyInfoDTO fzCompanyInfoDTO, long centerId, long orgId) {
        // 其他信息通过 企业认证补充页面收集
//        TbPolicyDto data = req.getTbPolicyDtoList().get(0);
        PrincipalDTO principalDTO = fzCompanyInfoDTO.getPrincipal();
//        TbInsuranceSchema insuranceSchema = data.getTbInsuranceSchema();
//        TbMainLiab mainLiab = data.getTbMainLiab();
//        TbProvinceSupply provinceSupply = data.getTbProvinceSupply();

        BidCustomerDO bidCustomer = new BidCustomerDO();
        bidCustomer.setCenterId(centerId);
        bidCustomer.setOrgId(orgId);
        bidCustomer.setBidderName(principalDTO.getCompanyName());
        bidCustomer.setBidderCreditCode(principalDTO.getSocialCreditCode());
        bidCustomer.setBidderContactName(fzGuaranteeApplyInfoDTO.getPrincipalName());
        bidCustomer.setBidderContactTel(fzGuaranteeApplyInfoDTO.getPrincipalPhone());
        bidCustomer.setBidderContactIdcard(fzGuaranteeApplyInfoDTO.getPrincipalIdCard());
        bidCustomer.setBidderContactIdcardType(IDType.ID_CARD.getType());
        bidCustomer.setBidderEamil(fzGuaranteeApplyInfoDTO.getPrincipalEmail());
        bidCustomer.setBidderAddress(principalDTO.getCompanyAddress());
        bidCustomer.setLegalPersonName(fzGuaranteeApplyInfoDTO.getPrincipalLegalPerson());
        bidCustomer.setLegalPersonIdcard(fzGuaranteeApplyInfoDTO.getPrincipalLegalIdCard());
        bidCustomer.setLegalPersonIdcardType(IDType.ID_CARD.getType());
        bidCustomer.setLegalPersonTel(fzGuaranteeApplyInfoDTO.getPrincipalLegalPhone());
        bidCustomer.setEnableAutoApprove(0);
        bidCustomer.setBlacklistFlag(0);
        bidCustomer.setBidderCapital(String.valueOf(wanYuan2yuanLong(principalDTO.getRegMoney())));
        bidCustomer.setBidderLegal(fzGuaranteeApplyInfoDTO.getPrincipalLegalPerson());
//        bidCustomer.setBidderBeginDate(null);
//        bidCustomer.setBidderEndDate(null);
        bidCustomer.setBidderRegAddress(principalDTO.getCompanyAddress());
//        bidCustomer.setBidderWebsite(null);
//        bidCustomer.setBidderIpcNo(null);
//        bidCustomer.setLegalBeginDate(null);
//        bidCustomer.setLegalEndDate(null);
        bidCustomer.setLicenseName(fzGuaranteeApplyInfoDTO.getPrincipal());
        bidCustomer.setLicenseAccount(fzGuaranteeApplyInfoDTO.getPrincipalAccountBankNo());
        bidCustomer.setLicenseLegal(fzGuaranteeApplyInfoDTO.getPrincipalLegalPerson());
        bidCustomer.setLicenseBank(fzGuaranteeApplyInfoDTO.getPrincipalAccountBankName());
//        bidCustomer.setLicenseCheckNo(null);
//        bidCustomer.setLicenseNo(null);
        bidCustomer.setStatus(BidCustomerStatus.NORMAL.getStatus());
//        bidCustomer.setAuditDesc(null);
//        bidCustomer.setFollowId(null);
//        bidCustomer.setBeiandiquCode(null);
        bidCustomer.setBankName(fzGuaranteeApplyInfoDTO.getPrincipalAccountBankName());
        bidCustomer.setBankCardNum(fzGuaranteeApplyInfoDTO.getPrincipalAccountBankNo());
        bidCustomer.setBankUserName(fzGuaranteeApplyInfoDTO.getPrincipal());
        bidCustomer.setComTelArea(fzGuaranteeApplyInfoDTO.getPrincipalAddress());
        bidCustomer.setComTelNum(fzGuaranteeApplyInfoDTO.getPrincipalPhone());
//        bidCustomer.setProvince(null);
//        bidCustomer.setCity(null);
//        bidCustomer.setDistrict(null);
//        bidCustomer.setEnterpriseId(null);
//        bidCustomer.setResultQueryTimes(null);

        return bidCustomer;

    }

    private UserDO buildUserInfo(FZGuaranteeApplyInfoDTO fzGuaranteeApplyInfoDTO) {
//        TbPolicyDto data = req.getTbPolicyDtoList().get(0);
//        TbInsuranceSchema insuranceSchema = data.getTbInsuranceSchema();
//        TbMainLiab mainLiab = data.getTbMainLiab();
//        TbProvinceSupply provinceSupply = data.getTbProvinceSupply();
        return UserDO.builder()
                .umLogin("0")
                .followId(fzGuaranteeApplyInfoDTO.getPrincipalSocialCreditCode())
                .username(fzGuaranteeApplyInfoDTO.getPrincipalSocialCreditCode())
                .mobileNo(fzGuaranteeApplyInfoDTO.getPrincipalPhone())//改成统一社会信用代码登录
                .name(fzGuaranteeApplyInfoDTO.getPrincipal())
                .type(UserType.BIDDER.getType())
                .status(UserStatusEnum.NORMAL.name())
                .orgCode("-1")
                .gmtCreate(new Date())
                .gmtModified(new Date())
                .build();
    }

    private ProjectInfoDO buildProjectInfo(FZGuaranteeApplyInfoDTO fzGuaranteeApplyInfoDTO, long centerId, long orgId) {
//        TbPolicyDto data = req.getTbPolicyDtoList().get(0);
//        TbInsuranceSchema insuranceSchema = data.getTbInsuranceSchema();
//        TbMainLiab mainLiab = data.getTbMainLiab();
//        TbProvinceSupply provinceSupply = data.getTbProvinceSupply();

        String projectCode = fzGuaranteeApplyInfoDTO.getProjectNumber();
        String projectName = fzGuaranteeApplyInfoDTO.getProjectName();

        return ProjectInfoDO.builder()
                .centerId(centerId).orgId(orgId)
                .projectCode(projectCode).projectName(projectName)
                .sectionCode(fzGuaranteeApplyInfoDTO.getBlockNumber())
                .sectionName(fzGuaranteeApplyInfoDTO.getBlockName())
                .contractReckonPrice(wanYuan2fenLong(fzGuaranteeApplyInfoDTO.getContractReckonAmount()))
                .tenderer(fzGuaranteeApplyInfoDTO.getCreditor())
                .tendererAddress(fzGuaranteeApplyInfoDTO.getCreditorAddress())
                .tendererCreditCode(fzGuaranteeApplyInfoDTO.getCreditorSocialCreditCode())
                .tendererBankOpenbank(fzGuaranteeApplyInfoDTO.getCreditorAccountBankName())
                .tendererBankCode(fzGuaranteeApplyInfoDTO.getCreditorAccountBankNo())
                .tendererBankAccount(fzGuaranteeApplyInfoDTO.getCreditor())
                .tendererContact(fzGuaranteeApplyInfoDTO.getCreditorName())
                .tendererContactTel(fzGuaranteeApplyInfoDTO.getCreditorPhone())
                .cityCode(fzGuaranteeApplyInfoDTO.getProjectCityCode())
//                .tenderProjectType(fzGuaranteeApplyInfoDTO.getProjectType())
                .tenderProjectType(fzGuaranteeApplyInfoDTO.getProjectCategory())
                .bidOpenTime(DateUtil.parseDate(fzGuaranteeApplyInfoDTO.getBidDeadline(), "yyyy-MM-dd HH:mm"))//'开标时间'=投标截止日期
                .validPeriod(Integer.valueOf(fzGuaranteeApplyInfoDTO.getValidDay()))//投标有效期（单位：天）
                .bidBond(yuan2fenLong(fzGuaranteeApplyInfoDTO.getGuaranteeAmount()))
                .tenderNoticeUrl(fzGuaranteeApplyInfoDTO.getTenderNoticeUrl())
                .tenderFileUrl(fzGuaranteeApplyInfoDTO.getTenderFileUrl())
//                .tenderFileMd5(getTenderMD5(fzGuaranteeApplyInfoDTO.getTenderFileUrl()))//'招标方文件md5校验值'
                .noticePubDate(StringUtils.isNotBlank(fzGuaranteeApplyInfoDTO.getTenderPublishDate()) ? DateUtil.parseDate(fzGuaranteeApplyInfoDTO.getTenderPublishDate(), "yyyy-MM-dd HH:mm:ss") : null)
//                .remark(null)//无
                .warnFlag(0)// '预警标识0正常 1出函机构无法受理该项目',
                .sourceFlag(0)// '信息来源0自动 1手动',
                .gmtCreate(Date.from(Instant.now()))
                .build();
    }

    private List<FilePushReqDTO.FileInfo> buildFileInfo(FZGuaranteeApplyInfoDTO fzGuaranteeApplyInfoDTO, FZCompanyInfoDTO fzCompanyInfoDTO) {
        List<GuaranteeSignFileDTO> guaranteeSignFileDTOS = JSONArray.parseArray(fzGuaranteeApplyInfoDTO.getGuaranteeSignFiles(), GuaranteeSignFileDTO.class);
        Map<String, GuaranteeSignFileDTO> guaranteeSignFileMap = guaranteeSignFileDTOS.stream().collect(Collectors.toMap(
                GuaranteeSignFileDTO::getFileName, item -> item, (existing, replacement) -> existing));
        List<FilePushReqDTO.FileInfo> fileInfos = new ArrayList<>();
        FilePushReqDTO.FileInfo legalCertFileInfo = new FilePushReqDTO.FileInfo();
        legalCertFileInfo.setFileTypeName(FileTypeNameEnum.TYPE05.getFileTypeName());
        legalCertFileInfo.setFileType(FileTypeNameEnum.TYPE05.getFileTypeName());
        legalCertFileInfo.setUrl(fzCompanyInfoDTO.getPrincipal().getLegalIdentityCert());
        FilePushReqDTO.FileInfo legalOppositeCertFileInfo = new FilePushReqDTO.FileInfo();
        legalOppositeCertFileInfo.setFileTypeName(FileTypeNameEnum.TYPE06.getFileTypeName());
        legalOppositeCertFileInfo.setFileType(FileTypeNameEnum.TYPE06.getFileTypeName());
        legalOppositeCertFileInfo.setUrl(fzCompanyInfoDTO.getPrincipal().getLegalIdentityOppositeCert());
        if (StringUtils.isBlank(fzCompanyInfoDTO.getPrincipal().getLegalIdentityOppositeCert())) {
            legalOppositeCertFileInfo.setUrl(fzCompanyInfoDTO.getPrincipal().getLegalIdentityCert());
        }
        fileInfos.add(legalCertFileInfo);
        fileInfos.add(legalOppositeCertFileInfo);

        FilePushReqDTO.FileInfo lFileInfo = new FilePushReqDTO.FileInfo();
        lFileInfo.setUrl(guaranteeSignFileMap.get(FileTypeNameEnum.TYPE03.getFileTypeName()).getFileUrl());
        lFileInfo.setFileTypeName(FileTypeNameEnum.TYPE03.getFileTypeName());
        FilePushReqDTO.FileInfo qFileInfo = new FilePushReqDTO.FileInfo();
        qFileInfo.setUrl(guaranteeSignFileMap.get(FileTypeNameEnum.TYPE04.getFileTypeName()).getFileUrl());
        qFileInfo.setFileTypeName(FileTypeNameEnum.TYPE04.getFileTypeName());
        fileInfos.add(lFileInfo);
        fileInfos.add(qFileInfo);
        return fileInfos;
    }

    public String getTenderMD5(String tenderFileUrl) {
        String md5Hex = null;
        try {
            URL url = new URL(tenderFileUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream in = conn.getInputStream();
            md5Hex = DigestUtils.md5Hex(in);
        } catch (Exception e) {
            log.error("计算招标文件MD5失败：{}", e.getMessage(), e);
        }
        return md5Hex;
    }

    private String genTenderFileMd5(String sectionCode, Long centerId, Long orgId, String tenderFileUrl) {
        String tenderFileMd5 = null;
        try {
            if (!StringUtils.isEmpty(tenderFileUrl)) {
                ProjectInfoDO projectInfo = projectInfoService.getBySectionCode(sectionCode, null, centerId, orgId);
                if (projectInfo == null || StringUtils.isEmpty(projectInfo.getTenderFileMd5())) {
                    //download file
                    Path tmpPath = elgResourceService.downloadFile(tenderFileUrl);

                    String relativePath = elgResourceService.transferAndSaveFile(tmpPath, "ofd", "tenderFile", "标段" + sectionCode + "招标文件");
                    Path savePath = elgResourceService.getAbsolutePath(relativePath);
                    tenderFileMd5 = elgResourceService.getFileMD5AsHex(savePath);
                    try {
                        Files.deleteIfExists(tmpPath);
                    } catch (IOException e) {
                        log.error("删除临时招标文件异常：{}", e.getMessage(), e);
                    }
                } else {
                    tenderFileMd5 = projectInfo.getTenderFileMd5();
                }
            }
        } catch (Exception e) {
            log.error("下载招标文件失败：{}", e.getMessage(), e);
        }
        return tenderFileMd5;
    }

    private Long getYouXiMZGuaranteeFee(Long projectAmount) {
        if (projectAmount < 2000000L) {
            return 10000L;
        } else if (projectAmount < 4000000L) {
            return 15000L;
        } else if (projectAmount < 14000000L) {
            return 20000L;
        } else {
            return Math.round(projectAmount * 0.0015);
        }
    }

    private void downloadFile(AcceptOrderInfoDO acceptOrderInfo, FilePushReqDTO.FileInfo fileInfo) throws Exception {
        String fileTypeName = fileInfo.getFileTypeName();
        AttachmentFileType attachmentFileType = FileTypeNameEnum.toGuaranteeAttachmentFileType(fileTypeName);
        CustomerAttachmentTypeEnum customerAttachmentTypeEnum = FileTypeNameEnum.toCustomerAttachmentFileType(fileTypeName);
        if (attachmentFileType != null) {
            this.saveOrUpdateGuaranteeAttachInfo(attachmentFileType, acceptOrderInfo, fileInfo);
        } else if (customerAttachmentTypeEnum != null) {
            this.saveOrUpdateCustomerAttachInfo(customerAttachmentTypeEnum, acceptOrderInfo, fileInfo);
        }

    }

    private void saveOrUpdateCustomerAttachInfo(CustomerAttachmentTypeEnum customerAttachmentType, AcceptOrderInfoDO acceptOrderInfo, FilePushReqDTO.FileInfo fileInfo) throws Exception {
        String fileUrl = fileInfo.getUrl();
        String md5Value = fileInfo.getMd5Value();
        Long bidCustomerId = acceptOrderInfo.getBidCustomerId();
        CustomerAttachmentDO customerAttachment = customerAttachmentService.getCustomerAttachment(bidCustomerId, customerAttachmentType);
        if (customerAttachment != null) {
            md5Value = customerAttachment.getFileMd5();
        }
        if (customerAttachment == null) {
            Path tmpPath = elgResourceService.downloadFile(fileUrl);
//            String relativePath = elgResourceService.transferAndSaveFile(tmpPath, "ofd", bidCustomerId.toString(), fileInfo.getFileTypeName());
            String relativePath = UUID.randomUUID().toString() + "." + elgResourceService.getFileType(tmpPath);
            md5Value = elgResourceService.getFileMD5AsHex(tmpPath);
            Path registerDir = Paths.get(imageUploadConfig.getPath(), Constants.REGIST_IMAGE_PATH);
            if (Files.notExists(registerDir)) {
                Files.createDirectories(registerDir);
            }
            Path registerImg = registerDir.resolve(relativePath);
            Files.copy(tmpPath, registerImg, StandardCopyOption.REPLACE_EXISTING);

            Files.deleteIfExists(tmpPath);

            customerAttachment = new CustomerAttachmentDO();
            customerAttachment.setId(IdGenerate.getId());
            customerAttachment.setBidderId(bidCustomerId);
            customerAttachment.setAttachType(customerAttachmentType.getType());
            customerAttachment.setAttachPath(relativePath);
            customerAttachment.setAttachFileName(relativePath);
            customerAttachment.setFileMd5(md5Value);
            customerAttachment.setFileUrl(fileUrl);

            customerAttachmentService.insert(customerAttachment);
        } else if (md5Value == null || !md5Value.equalsIgnoreCase(customerAttachment.getFileMd5())) {
            Path tmpPath = elgResourceService.downloadFile(fileUrl);
//            String relativePath = elgResourceService.transferAndSaveFile(tmpPath, "ofd", bidCustomerId.toString(), fileInfo.getFileTypeName());
            String relativePath = UUID.randomUUID().toString() + "." + elgResourceService.getFileType(tmpPath);
            md5Value = elgResourceService.getFileMD5AsHex(tmpPath);
            Path registerDir = Paths.get(imageUploadConfig.getPath(), Constants.REGIST_IMAGE_PATH);
            if (Files.notExists(registerDir)) {
                Files.createDirectories(registerDir);
            }
            Path registerImg = registerDir.resolve(relativePath);
            Files.copy(tmpPath, registerImg, StandardCopyOption.REPLACE_EXISTING);

            Files.deleteIfExists(tmpPath);


            customerAttachment.setBidderId(bidCustomerId);
            customerAttachment.setAttachType(customerAttachmentType.getType());
            customerAttachment.setAttachPath(relativePath);
            customerAttachment.setAttachFileName(relativePath);
            customerAttachment.setFileMd5(md5Value);
            customerAttachment.setFileUrl(fileUrl);

            customerAttachmentService.updateById(customerAttachment);
        }

    }

    private void saveOrUpdateGuaranteeAttachInfo(AttachmentFileType attachmentFileType, AcceptOrderInfoDO acceptOrderInfo, FilePushReqDTO.FileInfo fileInfo) throws Exception {
        String fileUrl = fileInfo.getUrl();
        String md5Value = fileInfo.getMd5Value();
        String acceptOrderNo = acceptOrderInfo.getAcceptOrderNo();
        GuaranteeAttachmentInfoDO guaranteeAttachmentInfo = guaranteeAttachmentInfoService.getTypeAttachmentByAcceptOrderNo(acceptOrderNo, attachmentFileType);
        if (guaranteeAttachmentInfo != null) {
            md5Value = guaranteeAttachmentInfo.getFileMd5();
        }
        if (guaranteeAttachmentInfo == null) {
            Path tmpPath = elgResourceService.downloadFile(fileUrl);
            String relativePath = elgResourceService.transferAndSaveFile(tmpPath, "ofd", acceptOrderNo, fileInfo.getFileTypeName());
            md5Value = elgResourceService.getFileMD5AsHex(elgResourceService.getAbsolutePath(relativePath));
            Files.deleteIfExists(tmpPath);

            guaranteeAttachmentInfo = new GuaranteeAttachmentInfoDO();
            guaranteeAttachmentInfo.setId(IdGenerate.getId());
            guaranteeAttachmentInfo.setCenterId(acceptOrderInfo.getCenterId());
            guaranteeAttachmentInfo.setOrgId(acceptOrderInfo.getOrgId());
            guaranteeAttachmentInfo.setAcceptOrderNo(acceptOrderInfo.getAcceptOrderNo());
            guaranteeAttachmentInfo.setType(attachmentFileType.getType());
            guaranteeAttachmentInfo.setFileName(fileInfo.getFileTypeName());
            guaranteeAttachmentInfo.setFileType(fileInfo.getFileType());
            guaranteeAttachmentInfo.setFileMd5(md5Value);
            guaranteeAttachmentInfo.setFilePath(relativePath);
            guaranteeAttachmentInfo.setRemark("新增" + attachmentFileType.getDesc());
            guaranteeAttachmentInfo.setFileUrl(fileInfo.getUrl());
            guaranteeAttachmentInfo.setFileId(fileInfo.getFileId());

            guaranteeAttachmentInfoService.insert(guaranteeAttachmentInfo);
        } else if (md5Value == null || !md5Value.equalsIgnoreCase(guaranteeAttachmentInfo.getFileMd5())) {
            Path tmpPath = elgResourceService.downloadFile(fileUrl);
            String relativePath = elgResourceService.transferAndSaveFile(tmpPath, "ofd", acceptOrderNo, fileInfo.getFileTypeName());
            md5Value = elgResourceService.getFileMD5AsHex(elgResourceService.getAbsolutePath(relativePath));
            Files.deleteIfExists(tmpPath);

            guaranteeAttachmentInfo.setCenterId(acceptOrderInfo.getCenterId());
            guaranteeAttachmentInfo.setOrgId(acceptOrderInfo.getOrgId());
            guaranteeAttachmentInfo.setAcceptOrderNo(acceptOrderInfo.getAcceptOrderNo());
            guaranteeAttachmentInfo.setType(attachmentFileType.getType());
            guaranteeAttachmentInfo.setFileName(fileInfo.getFileTypeName());
            guaranteeAttachmentInfo.setFileType(fileInfo.getFileType());
            guaranteeAttachmentInfo.setFileMd5(md5Value);
            guaranteeAttachmentInfo.setFilePath(relativePath);
            guaranteeAttachmentInfo.setRemark("更新" + attachmentFileType.getDesc());
            guaranteeAttachmentInfo.setFileUrl(fileInfo.getUrl());
            guaranteeAttachmentInfo.setFileId(fileInfo.getFileId());

            guaranteeAttachmentInfoService.updateById(guaranteeAttachmentInfo);
        }

    }

}
